<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF在线修改工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --success-color: #4cc9f0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fb;
            color: var(--dark-color);
        }
        
        .navbar {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 20px;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background-color: white;
            border-bottom: 1px solid #eaeaea;
            font-weight: 600;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0 !important;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .pdf-preview-wrapper {
            position: relative;
            width: 100%;
            min-height: 600px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background-color: #f9f9f9;
            overflow: auto;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 20px;
        }
        
        .pdf-container {
            position: relative;
            display: inline-block;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            background: white;
            cursor: crosshair;
        }
        
        .page-canvas {
            display: block;
            max-width: 100%;
            height: auto;
        }
        
        .selection-area {
            position: absolute;
            border: 2px solid var(--primary-color);
            background-color: rgba(67, 97, 238, 0.1);
            pointer-events: none;
            z-index: 10;
        }
        
        .selection-handle {
            position: absolute;
            width: 8px;
            height: 8px;
            background-color: var(--primary-color);
            border: 1px solid white;
            border-radius: 50%;
            pointer-events: all;
            z-index: 20;
        }
        
        .selection-handle.nw { top: -4px; left: -4px; cursor: nw-resize; }
        .selection-handle.ne { top: -4px; right: -4px; cursor: ne-resize; }
        .selection-handle.sw { bottom: -4px; left: -4px; cursor: sw-resize; }
        .selection-handle.se { bottom: -4px; right: -4px; cursor: se-resize; }
        .selection-handle.n { top: -4px; left: 50%; transform: translateX(-50%); cursor: n-resize; }
        .selection-handle.s { bottom: -4px; left: 50%; transform: translateX(-50%); cursor: s-resize; }
        .selection-handle.w { left: -4px; top: 50%; transform: translateY(-50%); cursor: w-resize; }
        .selection-handle.e { right: -4px; top: 50%; transform: translateY(-50%); cursor: e-resize; }
        
        .coordinates-display {
            position: absolute;
            top: 10px;
            left: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.8rem;
            z-index: 30;
        }
        
        .modification-item {
            border-left: 3px solid var(--primary-color);
            padding: 10px 15px;
            margin-bottom: 10px;
            background-color: #f8f9ff;
            border-radius: 0 5px 5px 0;
        }
        
        .progress-bar {
            background-color: var(--success-color);
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
            position: relative;
        }
        
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #e0e0e0;
            z-index: 1;
        }
        
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 5px;
            color: white;
        }
        
        .step.active .step-number {
            background-color: var(--primary-color);
        }
        
        .step.completed .step-number {
            background-color: var(--success-color);
        }
        
        .modification-controls {
            background-color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
        }
        
        .file-upload-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .file-upload-area:hover, .file-upload-area.dragover {
            border-color: var(--primary-color);
            background-color: #f0f4ff;
        }
        
        .file-info {
            background-color: #e8f4fe;
            border-radius: 6px;
            padding: 10px 15px;
            margin-top: 15px;
        }
        
        footer {
            background-color: var(--dark-color);
            color: white;
            padding: 30px 0;
            margin-top: 50px;
        }
        
        .operation-log {
            max-height: 200px;
            overflow-y: auto;
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 10px;
            font-size: 0.9rem;
        }
        
        .log-entry {
            padding: 5px 0;
            border-bottom: 1px solid #eaeaea;
        }
        
        .log-time {
            color: #6c757d;
            font-size: 0.8rem;
        }
        
        .page-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .zoom-controls {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .alert-area {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1050;
            min-width: 300px;
        }
        
        .preview-text {
            position: absolute;
            z-index: 15;
            pointer-events: none;
            white-space: nowrap;
            font-family: Arial, sans-serif;
        }
        
        .text-modification-preview {
            border: 1px dashed #4caf50;
            background-color: rgba(76, 175, 80, 0.1);
            padding: 2px 5px;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <!-- 加载遮罩 -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
        <div class="text-white mt-3" id="loadingText">处理中...</div>
    </div>

    <!-- 消息提示区域 -->
    <div class="alert-area" id="alertArea"></div>

    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="fas fa-file-pdf me-2"></i>PDF在线修改工具
            </a>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="container my-5">
        <div class="row">
            <div class="col-12">
                <h1 class="text-center mb-4">PDF在线修改工具</h1>
                <p class="text-center text-muted mb-5">上传您的PDF文件，选择需要修改的区域，轻松完成内容修改</p>
                
                <!-- 步骤指示器 -->
                <div class="step-indicator">
                    <div class="step active">
                        <div class="step-number">1</div>
                        <div>上传PDF</div>
                    </div>
                    <div class="step">
                        <div class="step-number">2</div>
                        <div>选择修改区域</div>
                    </div>
                    <div class="step">
                        <div class="step-number">3</div>
                        <div>设置修改内容</div>
                    </div>
                    <div class="step">
                        <div class="step-number">4</div>
                        <div>下载修改后文件</div>
                    </div>
                </div>
                
                <!-- 文件上传区域 -->
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-cloud-upload-alt me-2"></i>上传PDF文件
                    </div>
                    <div class="card-body">
                        <div class="file-upload-area" id="fileUploadArea">
                            <i class="fas fa-file-pdf fa-3x mb-3 text-primary"></i>
                            <h5>拖放PDF文件到此处或点击上传</h5>
                            <p class="text-muted">支持最大100MB的PDF文件</p>
                            <input type="file" id="fileInput" accept=".pdf" style="display: none;">
                            <button class="btn btn-primary mt-3" id="uploadButton">选择文件</button>
                        </div>
                        <div class="file-info d-none" id="fileInfo">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="fas fa-file-pdf me-2 text-primary"></i>
                                    <span id="fileName">example.pdf</span>
                                    <span class="text-muted ms-2" id="fileSize">(0 KB)</span>
                                </div>
                                <button class="btn btn-sm btn-outline-danger" id="removeFile">
                                    <i class="fas fa-times"></i> 移除
                                </button>
                            </div>
                            <div class="progress mt-2">
                                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- PDF预览和修改区域 -->
                <div class="card d-none" id="modificationArea">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-edit me-2"></i>PDF内容修改</span>
                        <div class="zoom-controls">
                            <button class="btn btn-sm btn-outline-secondary" id="zoomOut">
                                <i class="fas fa-search-minus"></i>
                            </button>
                            <span class="mx-2 text-muted" id="zoomLevel">100%</span>
                            <button class="btn btn-sm btn-outline-secondary" id="zoomIn">
                                <i class="fas fa-search-plus"></i>
                            </button>
                            <span class="ms-3">适合宽度:</span>
                            <button class="btn btn-sm btn-outline-primary ms-2" id="fitWidth">
                                <i class="fas fa-arrows-alt-h"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="pdf-preview-wrapper" id="pdfPreview">
                                    <div class="pdf-container" id="pdfContainer">
                                        <div class="coordinates-display d-none" id="coordinatesDisplay">
                                            X: 0, Y: 0
                                        </div>
                                        <canvas id="pdfCanvas" class="page-canvas"></canvas>
                                        <div class="selection-area d-none" id="selectionArea"></div>
                                        <!-- 文本预览区域 -->
                                        <div id="textPreviewContainer"></div>
                                    </div>
                                </div>
                                <div class="page-controls">
                                    <button class="btn btn-outline-primary" id="prevPage">
                                        <i class="fas fa-chevron-left me-1"></i>上一页
                                    </button>
                                    <span>第 <span id="currentPage">1</span> 页，共 <span id="totalPages">1</span> 页</span>
                                    <button class="btn btn-outline-primary" id="nextPage">
                                        下一页 <i class="fas fa-chevron-right ms-1"></i>
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" id="clearSelection">
                                        <i class="fas fa-times"></i> 清除选择
                                    </button>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="modification-controls">
                                    <h5>修改操作</h5>
                                    <div class="mb-3">
                                        <label class="form-label">选择修改类型</label>
                                        <select class="form-select" id="modificationType">
                                            <option value="text">文本替换</option>
                                            <option value="addText">添加文本</option>
                                            <option value="image">图片替换</option>
                                            <option value="watermark">添加水印</option>
                                            <option value="annotation">添加注释</option>
                                        </select>
                                    </div>
                                    
                                    <div id="textModification" class="modification-panel">
                                        <div class="mb-3">
                                            <label class="form-label">原文本内容</label>
                                            <textarea class="form-control" rows="2" placeholder="输入要替换的文本内容" id="originalText"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">新文本内容</label>
                                            <textarea class="form-control" rows="2" placeholder="输入替换后的文本内容" id="newText"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">字体</label>
                                            <select class="form-select" id="fontFamily">
                                                <option value="Arial">Arial</option>
                                                <option value="Helvetica">Helvetica</option>
                                                <option value="Times New Roman">Times New Roman</option>
                                                <option value="Courier New">Courier New</option>
                                                <option value="Verdana">Verdana</option>
                                            </select>
                                        </div>
                                        <div class="row">
                                            <div class="col-6">
                                                <label class="form-label">字号</label>
                                                <input type="number" class="form-control" id="fontSize" value="12" min="6" max="72">
                                            </div>
                                            <div class="col-6">
                                                <label class="form-label">颜色</label>
                                                <input type="color" class="form-control" id="fontColor" value="#000000">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div id="addTextModification" class="modification-panel d-none">
                                        <div class="mb-3">
                                            <label class="form-label">新增文本内容</label>
                                            <textarea class="form-control" rows="3" placeholder="输入要添加的文本内容" id="addTextContent"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">字体</label>
                                            <select class="form-select" id="addTextFontFamily">
                                                <option value="Arial">Arial</option>
                                                <option value="Helvetica">Helvetica</option>
                                                <option value="Times New Roman">Times New Roman</option>
                                                <option value="Courier New">Courier New</option>
                                                <option value="Verdana">Verdana</option>
                                            </select>
                                        </div>
                                        <div class="row">
                                            <div class="col-6">
                                                <label class="form-label">字号</label>
                                                <input type="number" class="form-control" id="addTextFontSize" value="14" min="6" max="72">
                                            </div>
                                            <div class="col-6">
                                                <label class="form-label">颜色</label>
                                                <input type="color" class="form-control" id="addTextFontColor" value="#000000">
                                            </div>
                                        </div>
                                        <div class="form-check mt-2">
                                            <input class="form-check-input" type="checkbox" id="addTextBold">
                                            <label class="form-check-label" for="addTextBold">
                                                粗体
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="addTextItalic">
                                            <label class="form-check-label" for="addTextItalic">
                                                斜体
                                            </label>
                                        </div>
                                        <button class="btn btn-outline-primary w-100 mt-3" id="previewTextButton">
                                            <i class="fas fa-eye me-1"></i> 预览文本效果
                                        </button>
                                    </div>
                                    
                                    <div id="imageModification" class="modification-panel d-none">
                                        <div class="mb-3">
                                            <label class="form-label">上传新图片</label>
                                            <input type="file" class="form-control" id="imageUpload" accept="image/*">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">缩放比例</label>
                                            <input type="range" class="form-range" id="imageScale" min="10" max="200" value="100">
                                            <div class="text-end"><span id="scaleValue">100%</span></div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">选择区域坐标</label>
                                        <div class="row">
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectX" placeholder="X坐标" readonly>
                                            </div>
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectY" placeholder="Y坐标" readonly>
                                            </div>
                                        </div>
                                        <div class="row mt-2">
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectWidth" placeholder="宽度" readonly>
                                            </div>
                                            <div class="col-6">
                                                <input type="number" class="form-control" id="selectHeight" placeholder="高度" readonly>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button class="btn btn-primary w-100 mt-3" id="addModification">
                                        <i class="fas fa-plus me-1"></i> 添加修改操作
                                    </button>
                                    
                                    <div class="mt-4">
                                        <h6>已添加的修改操作</h6>
                                        <div id="modificationList">
                                            <div class="text-muted text-center py-3">暂无修改操作</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 操作日志 -->
                <div class="card d-none" id="logArea">
                    <div class="card-header">
                        <i class="fas fa-list-alt me-2"></i>操作日志
                    </div>
                    <div class="card-body">
                        <div class="operation-log" id="operationLog">
                            <div class="log-entry">
                                <span class="log-time">09:30:15</span> - 系统就绪，等待上传PDF文件
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-outline-secondary" id="resetButton">
                        <i class="fas fa-redo me-1"></i> 重置
                    </button>
                    <div>
                        <button class="btn btn-outline-primary me-2" id="previewButton" disabled>
                            <i class="fas fa-eye me-1"></i> 预览修改
                        </button>
                        <button class="btn btn-success" id="downloadButton" disabled>
                            <i class="fas fa-download me-1"></i> 下载修改后的PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap & PDF.js -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <script>
        // 设置PDF.js worker路径
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';
        
        // 后端API配置
        const API_CONFIG = {
            baseURL: 'http://localhost:8080',
            preview: '/aaa/bbb',
            download: '/aaa/ccc'
        };
        
        // 全局变量
        let currentPdf = null;
        let currentPageNum = 1;
        let totalPages = 0;
        let scale = 1.0;
        let modifications = [];
        let isSelecting = false;
        let selectionStart = { x: 0, y: 0 };
        let currentSelection = null;
        let isResizing = false;
        let resizeHandle = null;
        let currentFile = null;
        let textPreview = null;
        
        // DOM元素
        const fileInput = document.getElementById('fileInput');
        const uploadButton = document.getElementById('uploadButton');
        const fileUploadArea = document.getElementById('fileUploadArea');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const removeFile = document.getElementById('removeFile');
        const modificationArea = document.getElementById('modificationArea');
        const pdfCanvas = document.getElementById('pdfCanvas');
        const pdfContainer = document.getElementById('pdfContainer');
        const selectionArea = document.getElementById('selectionArea');
        const textPreviewContainer = document.getElementById('textPreviewContainer');
        const currentPageSpan = document.getElementById('currentPage');
        const totalPagesSpan = document.getElementById('totalPages');
        const prevPageButton = document.getElementById('prevPage');
        const nextPageButton = document.getElementById('nextPage');
        const zoomInButton = document.getElementById('zoomIn');
        const zoomOutButton = document.getElementById('zoomOut');
        const fitWidthButton = document.getElementById('fitWidth');
        const zoomLevel = document.getElementById('zoomLevel');
        const modificationType = document.getElementById('modificationType');
        const modificationPanels = document.querySelectorAll('.modification-panel');
        const addModificationButton = document.getElementById('addModification');
        const modificationList = document.getElementById('modificationList');
        const logArea = document.getElementById('logArea');
        const operationLog = document.getElementById('operationLog');
        const previewButton = document.getElementById('previewButton');
        const downloadButton = document.getElementById('downloadButton');
        const resetButton = document.getElementById('resetButton');
        const scaleValue = document.getElementById('scaleValue');
        const scaleSlider = document.getElementById('imageScale');
        const coordinatesDisplay = document.getElementById('coordinatesDisplay');
        const clearSelectionButton = document.getElementById('clearSelection');
        const selectX = document.getElementById('selectX');
        const selectY = document.getElementById('selectY');
        const selectWidth = document.getElementById('selectWidth');
        const selectHeight = document.getElementById('selectHeight');
        const loadingOverlay = document.getElementById('loadingOverlay');
        const loadingText = document.getElementById('loadingText');
        const alertArea = document.getElementById('alertArea');
        const originalText = document.getElementById('originalText');
        const newText = document.getElementById('newText');
        const fontFamily = document.getElementById('fontFamily');
        const fontSize = document.getElementById('fontSize');
        const fontColor = document.getElementById('fontColor');
        const addTextContent = document.getElementById('addTextContent');
        const addTextFontFamily = document.getElementById('addTextFontFamily');
        const addTextFontSize = document.getElementById('addTextFontSize');
        const addTextFontColor = document.getElementById('addTextFontColor');
        const addTextBold = document.getElementById('addTextBold');
        const addTextItalic = document.getElementById('addTextItalic');
        const previewTextButton = document.getElementById('previewTextButton');
        const imageUpload = document.getElementById('imageUpload');
        
        // 事件监听器
        document.addEventListener('DOMContentLoaded', function() {
            uploadButton.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', handleFileSelect);
            
            fileUploadArea.addEventListener('click', function(e) {
                if (e.target !== uploadButton) {
                    fileInput.click();
                }
            });
            
            fileUploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                fileUploadArea.classList.add('dragover');
            });
            
            fileUploadArea.addEventListener('dragleave', () => {
                fileUploadArea.classList.remove('dragover');
            });
            
            fileUploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                fileUploadArea.classList.remove('dragover');
                if (e.dataTransfer.files.length) {
                    fileInput.files = e.dataTransfer.files;
                    handleFileSelect();
                }
            });
            
            removeFile.addEventListener('click', resetApp);
            prevPageButton.addEventListener('click', () => changePage(-1));
            nextPageButton.addEventListener('click', () => changePage(1));
            zoomInButton.addEventListener('click', () => changeZoom(0.2));
            zoomOutButton.addEventListener('click', () => changeZoom(-0.2));
            fitWidthButton.addEventListener('click', fitToWidth);
            modificationType.addEventListener('change', showModificationPanel);
            addModificationButton.addEventListener('click', addModification);
            previewButton.addEventListener('click', previewModifications);
            downloadButton.addEventListener('click', downloadModifiedPdf);
            resetButton.addEventListener('click', resetApp);
            scaleSlider.addEventListener('input', (e) => {
                scaleValue.textContent = e.target.value + '%';
            });
            clearSelectionButton.addEventListener('click', clearSelection);
            previewTextButton.addEventListener('click', previewTextOnCanvas);
            
            // 文本预览相关事件
            addTextContent.addEventListener('input', updateTextPreview);
            addTextFontFamily.addEventListener('change', updateTextPreview);
            addTextFontSize.addEventListener('input', updateTextPreview);
            addTextFontColor.addEventListener('input', updateTextPreview);
            addTextBold.addEventListener('change', updateTextPreview);
            addTextItalic.addEventListener('change', updateTextPreview);
            
            // 初始化事件监听
            pdfContainer.addEventListener('mousedown', startSelection);
            pdfContainer.addEventListener('mousemove', handleMouseMove);
            pdfContainer.addEventListener('mouseup', endSelection);
            pdfContainer.addEventListener('mouseleave', () => {
                coordinatesDisplay.classList.add('d-none');
            });
            
            addLogEntry('系统初始化完成');
        });
        
        // 修复坐标转换函数
        function getCanvasCoordinates(clientX, clientY) {
            const canvasRect = pdfCanvas.getBoundingClientRect();
            const scaleX = pdfCanvas.width / canvasRect.width;
            const scaleY = pdfCanvas.height / canvasRect.height;
            
            return {
                x: (clientX - canvasRect.left) * scaleX,
                y: (clientY - canvasRect.top) * scaleY,
                canvasRect: canvasRect
            };
        }
        
        // 修复选择功能
        function startSelection(e) {
            if (!currentPdf) return;
            
            const coords = getCanvasCoordinates(e.clientX, e.clientY);
            
            if (coords.x < 0 || coords.y < 0 || 
                coords.x > pdfCanvas.width || coords.y > pdfCanvas.height) {
                return;
            }
            
            if (currentSelection && isResizingHandle(coords.x, coords.y)) {
                isResizing = true;
                return;
            }
            
            isSelecting = true;
            selectionStart = { x: coords.x, y: coords.y };
            
            currentSelection = {
                x: coords.x,
                y: coords.y,
                width: 0,
                height: 0,
                page: currentPageNum
            };
            
            updateSelectionArea();
            selectionArea.classList.remove('d-none');
        }
        
        function handleMouseMove(e) {
            if (!currentPdf) return;
            
            const coords = getCanvasCoordinates(e.clientX, e.clientY);
            
            // 更新坐标显示
            if (coords.x >= 0 && coords.y >= 0 && 
                coords.x <= pdfCanvas.width && coords.y <= pdfCanvas.height) {
                coordinatesDisplay.textContent = `X: ${Math.round(coords.x)}, Y: ${Math.round(coords.y)}`;
                coordinatesDisplay.classList.remove('d-none');
                
                const displayX = Math.min(coords.canvasRect.width - 100, Math.max(10, coords.x / (pdfCanvas.width / coords.canvasRect.width)));
                const displayY = Math.max(30, coords.y / (pdfCanvas.height / coords.canvasRect.height) - 40);
                
                coordinatesDisplay.style.left = displayX + 'px';
                coordinatesDisplay.style.top = displayY + 'px';
            } else {
                coordinatesDisplay.classList.add('d-none');
            }
            
            if (isResizing) {
                handleResize(coords.x, coords.y);
            } else if (isSelecting && currentSelection) {
                const width = coords.x - selectionStart.x;
                const height = coords.y - selectionStart.y;
                
                currentSelection.x = width >= 0 ? selectionStart.x : coords.x;
                currentSelection.y = height >= 0 ? selectionStart.y : coords.y;
                currentSelection.width = Math.abs(width);
                currentSelection.height = Math.abs(height);
                
                // 边界检查
                if (currentSelection.x < 0) {
                    currentSelection.width += currentSelection.x;
                    currentSelection.x = 0;
                }
                if (currentSelection.y < 0) {
                    currentSelection.height += currentSelection.y;
                    currentSelection.y = 0;
                }
                if (currentSelection.x + currentSelection.width > pdfCanvas.width) {
                    currentSelection.width = pdfCanvas.width - currentSelection.x;
                }
                if (currentSelection.y + currentSelection.height > pdfCanvas.height) {
                    currentSelection.height = pdfCanvas.height - currentSelection.y;
                }
                
                // 最小尺寸限制
                if (currentSelection.width < 5) currentSelection.width = 5;
                if (currentSelection.height < 5) currentSelection.height = 5;
                
                updateSelectionArea();
                updateCoordinateInputs();
            }
        }
        
        function updateSelectionArea() {
            if (!currentSelection) return;
            
            const canvasRect = pdfCanvas.getBoundingClientRect();
            const scaleX = canvasRect.width / pdfCanvas.width;
            const scaleY = canvasRect.height / pdfCanvas.height;
            
            selectionArea.style.left = (currentSelection.x * scaleX) + 'px';
            selectionArea.style.top = (currentSelection.y * scaleY) + 'px';
            selectionArea.style.width = (currentSelection.width * scaleX) + 'px';
            selectionArea.style.height = (currentSelection.height * scaleY) + 'px';
            
            addResizeHandles();
        }
        
        // 文本预览功能
        function previewTextOnCanvas() {
            if (!currentSelection || currentSelection.width < 10 || currentSelection.height < 10) {
                showAlert('请先选择一个有效的区域', 'warning');
                return;
            }
            
            const text = addTextContent.value.trim();
            if (!text) {
                showAlert('请输入要添加的文本内容', 'warning');
                return;
            }
            
            // 清除之前的预览
            clearTextPreview();
            
            // 创建文本预览元素
            textPreview = document.createElement('div');
            textPreview.className = 'preview-text text-modification-preview';
            
            // 设置文本样式
            const fontSize = parseInt(addTextFontSize.value);
            const fontFamily = addTextFontFamily.value;
            const color = addTextFontColor.value;
            let fontWeight = addTextBold.checked ? 'bold' : 'normal';
            let fontStyle = addTextItalic.checked ? 'italic' : 'normal';
            
            textPreview.style.fontFamily = fontFamily;
            textPreview.style.fontSize = fontSize + 'px';
            textPreview.style.color = color;
            textPreview.style.fontWeight = fontWeight;
            textPreview.style.fontStyle = fontStyle;
            textPreview.style.left = selectionArea.style.left;
            textPreview.style.top = selectionArea.style.top;
            textPreview.style.width = selectionArea.style.width;
            textPreview.style.height = selectionArea.style.height;
            textPreview.style.lineHeight = selectionArea.style.height;
            textPreview.style.textAlign = 'center';
            textPreview.textContent = text;
            
            textPreviewContainer.appendChild(textPreview);
            
            showAlert('文本预览已添加，可调整位置和样式', 'success');
        }
        
        function updateTextPreview() {
            if (textPreview) {
                previewTextOnCanvas();
            }
        }
        
        function clearTextPreview() {
            if (textPreview) {
                textPreview.remove();
                textPreview = null;
            }
        }
        
        // 修改添加修改操作函数
        function addModification() {
            const type = modificationType.value;
            
            if (type === 'addText') {
                if (!textPreview) {
                    showAlert('请先预览文本效果', 'warning');
                    return;
                }
                
                const modificationData = {
                    type: type,
                    page: currentPageNum,
                    x: Math.round(currentSelection.x),
                    y: Math.round(currentSelection.y),
                    width: Math.round(currentSelection.width),
                    height: Math.round(currentSelection.height),
                    text: addTextContent.value,
                    fontFamily: addTextFontFamily.value,
                    fontSize: parseInt(addTextFontSize.value),
                    color: addTextFontColor.value,
                    bold: addTextBold.checked,
                    italic: addTextItalic.checked,
                    description: `第${currentPageNum}页添加文本`
                };
                
                modifications.push({
                    id: Date.now(),
                    ...modificationData
                });
                
                // 将预览文本转换为永久显示
                textPreview.classList.remove('text-modification-preview');
                textPreview.style.border = 'none';
                textPreview.style.backgroundColor = 'transparent';
                
                updateModificationList();
                addLogEntry(`已添加文本: "${addTextContent.value}"`);
                showAlert('文本已添加到PDF', 'success');
                
                // 重置表单
                addTextContent.value = '';
                clearTextPreview();
                clearSelection();
                
            } else {
                // 原有的其他修改类型处理
                if (!currentSelection || currentSelection.width < 10 || currentSelection.height < 10) {
                    showAlert('请先选择一个有效的区域', 'warning');
                    return;
                }
                
                const modificationData = {
                    type: type,
                    page: currentPageNum,
                    x: Math.round(currentSelection.x),
                    y: Math.round(currentSelection.y),
                    width: Math.round(currentSelection.width),
                    height: Math.round(currentSelection.height),
                    description: `第${currentPageNum}页的${getModificationTypeText(type)}修改`
                };
                
                // 根据类型添加特定数据
                switch (type) {
                    case 'text':
                        modificationData.originalText = originalText.value;
                        modificationData.newText = newText.value;
                        modificationData.fontFamily = fontFamily.value;
                        modificationData.fontSize = fontSize.value;
                        modificationData.fontColor = fontColor.value;
                        break;
                    case 'image':
                        modificationData.imageScale = scaleSlider.value;
                        break;
                    case 'watermark':
                        modificationData.watermarkText = newText.value || '水印';
                        break;
                    case 'annotation':
                        modificationData.annotationText = newText.value;
                        break;
                }
                
                modifications.push({
                    id: Date.now(),
                    ...modificationData
                });
                
                updateModificationList();
                addLogEntry(`已添加修改操作: ${modificationData.description}`);
                showAlert('修改操作已添加', 'success');
            }
        }
        
        // 修改显示修改面板函数
        function showModificationPanel() {
            const type = modificationType.value;
            modificationPanels.forEach(panel => panel.classList.add('d-none'));
            
            if (type === 'addText') {
                document.getElementById('addTextModification').classList.remove('d-none');
                // 清除选择区域预览
                clearTextPreview();
            } else {
                document.getElementById('textModification').classList.remove('d-none');
            }
            
            // 显示其他面板
            if (type === 'image') {
                document.getElementById('imageModification').classList.remove('d-none');
            }
        }
        
        // 修改类型文本
        function getModificationTypeText(type) {
            const types = {
                'text': '文本替换',
                'addText': '添加文本',
                'image': '图片替换',
                'watermark': '添加水印',
                'annotation': '添加注释'
            };
            return types[type] || '未知';
        }
        
        // 修改清除选择函数
        function clearSelection() {
            currentSelection = null;
            selectionArea.classList.add('d-none');
            document.querySelectorAll('.selection-handle').forEach(handle => handle.remove());
            
            selectX.value = '';
            selectY.value = '';
            selectWidth.value = '';
            selectHeight.value = '';
            
            clearTextPreview();
            
            addLogEntry('已清除选择区域');
        }
        
        // 修改重置函数
        function resetApp() {
            currentPdf = null;
            currentPageNum = 1;
            totalPages = 0;
            scale = 1.0;
            modifications = [];
            currentSelection = null;
            currentFile = null;
            
            fileInput.value = '';
            fileInfo.classList.add('d-none');
            modificationArea.classList.add('d-none');
            logArea.classList.add('d-none');
            selectionArea.classList.add('d-none');
            modificationList.innerHTML = '<div class="text-muted text-center py-3">暂无修改操作</div>';
            previewButton.disabled = true;
            downloadButton.disabled = true;
            
            // 清空表单和预览
            originalText.value = '';
            newText.value = '';
            addTextContent.value = '';
            fontFamily.value = 'Arial';
            fontSize.value = '12';
            fontColor.value = '#000000';
            addTextFontFamily.value = 'Arial';
            addTextFontSize.value = '14';
            addTextFontColor.value = '#000000';
            addTextBold.checked = false;
            addTextItalic.checked = false;
            
            clearTextPreview();
            textPreviewContainer.innerHTML = '';
            
            updateStepIndicator(1);
            addLogEntry('系统已重置，等待上传新的PDF文件');
            showAlert('系统已重置', 'info');
        }
        
        // 其他函数保持不变...
        // [此处保留原有的其他函数，如API调用、工具函数等]
        
        // 示例函数 - 实际使用时需要完整实现
        function handleFileSelect() {
            if (!fileInput.files.length) return;
            
            const file = fileInput.files[0];
            currentFile = file;
            
            if (file.type !== 'application/pdf') {
                alert('请选择PDF文件');
                return;
            }
            
            // 显示文件信息
            fileName.textContent = file.name;
            fileSize.textContent = `(${(file.size / 1024).toFixed(1)} KB)`;
            fileInfo.classList.remove('d-none');
            
            // 模拟上传进度
            const progressBar = fileInfo.querySelector('.progress-bar');
            let progress = 0;
            const interval = setInterval(() => {
                progress += 5;
                progressBar.style.width = `${progress}%`;
                if (progress >= 100) {
                    clearInterval(interval);
                    loadPdf(file);
                }
            }, 100);
            
            addLogEntry(`已上传PDF文件: ${file.name}`);
        }
        
        function loadPdf(file) {
            const fileReader = new FileReader();
            
            fileReader.onload = function() {
                const typedarray = new Uint8Array(this.result);
                
                pdfjsLib.getDocument(typedarray).promise.then(pdf => {
                    currentPdf = pdf;
                    totalPages = pdf.numPages;
                    totalPagesSpan.textContent = totalPages;
                    currentPageNum = 1;
                    
                    modificationArea.classList.remove('d-none');
                    logArea.classList.remove('d-none');
                    
                    updateStepIndicator(2);
                    renderPage(currentPageNum);
                    
                    addLogEntry('PDF文件加载成功，共' + totalPages + '页');
                    previewButton.disabled = false;
                    downloadButton.disabled = false;
                }).catch(error => {
                    console.error('Error loading PDF:', error);
                    addLogEntry('PDF文件加载失败: ' + error.message);
                    showAlert('PDF文件加载失败', 'danger');
                });
            };
            
            fileReader.readAsArrayBuffer(file);
        }
        
        // 其他必要函数...
    </script>
</body>
</html>